package com.luyun.frogpay.base.network.request;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.luyun.frogpay.base.network.api.RetrofitService;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

import static com.luyun.frogpay.base.global.Constants.BASE_URL;
import static com.luyun.frogpay.base.global.Constants.HTTP_TIME;

/**
 * Created by 赵星宇 on 2018/1/26.
 */

public class RetrofitFactory {
    private static RetrofitFactory retrofitFactory;
    private static RetrofitService retrofitService;
    Gson gson = new GsonBuilder()
            .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
            .serializeNulls()
            .create();
    private RetrofitFactory(){
        OkHttpClient mOkHttpClient = new OkHttpClient.Builder()
                .authenticator(new TokenAuthenticator())
                .connectTimeout(HTTP_TIME, TimeUnit.SECONDS)
                .readTimeout(HTTP_TIME, TimeUnit.SECONDS)
                .writeTimeout(HTTP_TIME, TimeUnit.SECONDS)
                .addInterceptor(InterceptorUtil.HeaderInterceptor())
                .addInterceptor(InterceptorUtil.LogInterceptor())//添加日志拦截器
                .addNetworkInterceptor(InterceptorUtil.addProgress())//添加进度
                .build();

        Retrofit mRetrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create(gson))//添加gson转换器
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())//添加rxjava转换器
                .client(mOkHttpClient)
                .build();
        retrofitService = mRetrofit.create(RetrofitService.class);
    }

    public static RetrofitFactory getInstence(){
        if (retrofitFactory == null){
            synchronized (RetrofitFactory.class) {
                if (retrofitFactory == null) {
                    retrofitFactory = new RetrofitFactory();
                }
            }
        }
        return retrofitFactory;
    }
    public RetrofitService API(){
        return retrofitService;
    }
}
